package com.zja.service.Impl;

import com.zja.dao.CommentDao;
import com.zja.dao.Impl.CommentDaoImpl;
import com.zja.model.Comment;
import com.zja.service.CommentService;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JA
 * @date: 2025/5/5
 * description:
 */
public class CommentServiceImpl implements CommentService {
    private final CommentDao commentDao = new CommentDaoImpl();

    @Override
    public boolean addComment(Comment comment) {
        comment.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        comment.setUpdatedAt(comment.getCreatedAt());
        return commentDao.insert(comment);
    }

    @Override
    public List<Comment> getCommentsByArticleId(Long articleId) {
        return commentDao.selectAll()
                .stream()
                .filter(c -> c.getArticleId().equals(articleId))
                .toList();
    }

    @Override
    public boolean deleteComment(Long commentId) {
        return commentDao.deleteById(commentId);
    }

    @Override
    public boolean updateComment(Comment comment) {
        comment.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        return commentDao.update(comment);
    }

    @Override
    public Comment getCommentById(Long id) {
        return commentDao.selectById(id);
    }

    /**
     * 构造指定文章的评论树
     */
    @Override
    public List<Comment> getCommentTreeByArticleId(Long articleId) {
        List<Comment> allComments = commentDao.selectAllByArticleId(articleId);
        Map<Long, Comment> commentMap = new HashMap<>();
        List<Comment> roots = new ArrayList<>();

        // 建立 ID -> Comment 映射
        for (Comment comment : allComments) {
            // 初始化 replies 列表
            comment.setReplies(new ArrayList<>());
            commentMap.put(comment.getId(), comment);
        }

        // 构建树结构
        for (Comment comment : allComments) {
            if (comment.getParentCommentId() == null) {
                // 顶级评论
                roots.add(comment);
            } else {
                Comment parent = commentMap.get(comment.getParentCommentId());
                if (parent != null) {
                    // 添加到父评论的 replies 中
                    parent.getReplies().add(comment);
                }
            }
        }

        return roots;
    }
}
